using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Resources;

namespace Rally_Dekstop
{
    public partial class frmTestCaseExecution : Form
    {
        private ResourceManager m_ResourceManager = Localizer.getInstance().GetResourceManager();
        private frmTestResultEditor editresult = null;
        public string filename = null;
        private bool dataupdated = false;
     
        
        public bool populatedata = false;
        public frmTestCaseExecution()
        {
            InitializeComponent();
            this.MdiParent = Rally_Dekstop.Program.RallyMain;
            this.WindowState = FormWindowState.Normal;
            ClearFormItems();
            htmlEditor_Desc.IsEditMode = htmlEditor_Expected.IsEditMode = htmlEditor_Validation.IsEditMode = false;


        }

        private void DataViewer_Load(object sender, EventArgs e)
        {
            
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (listView_testresults.CheckedItems.Count < 1)
            {
                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/NoRecordsSelected"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //MessageBox.Show("Please select at least one record...", "Rally Desk");
                return;
            }

            IRallyService service = null;
            if (RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceType == "UseCase")
                service = new RallyAPIUseCase(RallyDesk.url);
            else
                service = new RallyAPIUserStory(RallyDesk.url);

            string[] ResultRecord = new string[7];

            string result;
            int Recordcount = 0;
            int Count = 0;
            Recordcount = listView_testresults.Items.Count;
            Logs Newlog = new Logs();
            ProgressWatch Progress1 = new ProgressWatch("Test Results Upload in Progress...");

            Newlog.textBox_log.Text = "Test Result Update Log:" + Environment.NewLine + Environment.NewLine;

            this.Enabled = false;
            Progress1.Show();
            Progress1.PBar.Maximum = 200;// [your known value.]
            Progress1.PBar.Minimum = 0;
            Progress1.PBar.Step = 10;
            Progress1.PBar.PerformStep();
            Progress1.PBar.Step = 200 / Recordcount;
            if (Progress1.WindowState == FormWindowState.Maximized)
                Progress1.WindowState = FormWindowState.Normal;
            Application.DoEvents();
            foreach (ListViewItem tcitem in listView_testresults.Items)
            {
                if (Progress1.abortCheck != true)
                {
                    if (tcitem.Checked == true)
                    {
                        Count++;
                        ResultRecord[0] = tcitem.SubItems[0].Text;
                        ResultRecord[1] = tcitem.SubItems[2].Text;
                        ResultRecord[2] = RallyDesk.Username;
                        ResultRecord[3] = tcitem.SubItems[3].Text;
                        ResultRecord[4] = tcitem.SubItems[4].Text;
                        ResultRecord[5] = tcitem.SubItems[5].Text;
                        ResultRecord[6] = RallyDesk.CURRENTWORKSPACE.SelectedWorkSpaceRef;
                        //public bool CreateTestResult(string TestCaseID, string Verdict, string Tester,string Build, string Notes)
                       if (ResultRecord[0]!= string.Empty && ResultRecord[1]!= string.Empty)
                       {
                           result=service.CreateTestResult(ResultRecord);
                         if (result == string.Empty)
                        {
                            
                            Newlog.textBox_log.Text += "Result Updated for : " + ResultRecord[0] + Environment.NewLine;
                        }
                        else
                        {
                            Newlog.textBox_log.Text += "Invalid Data for " + ResultRecord[0] + " :" + result + Environment.NewLine; 
                        }


                       }
                        else
                        {
                            Newlog.textBox_log.Text += "Invalid Data for " + ResultRecord[0] + Environment.NewLine;
                        }

                        Progress1.PBar.PerformStep();

                    }
                    Application.DoEvents();
                }
                else
                    break;

            }

            Newlog.textBox_log.Text += Environment.NewLine;
            Newlog.textBox_log.Text += Convert.ToString(Count) + " Records Processed." + Environment.NewLine;
            Newlog.textBox_log.Text += "Upload Complete." + Environment.NewLine;


            Progress1.Close();
            this.Enabled = true;
            Newlog.ShowDialog();


        }

        private void listView_testresults_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView_testresults.Items.Count > 0)
            {
                if (listView_testresults.CheckedItems.Count < listView_testresults.Items.Count)
                {
                    SelectAll_checkBox.CheckState = CheckState.Unchecked;
                    SelectAll_checkBox.Enabled = true;
                }
                else
                    SelectAll_checkBox.Enabled = false;

                Viewer();

            }
            else
                ClearFormItems();

        }
        private void Viewer()
        {
            if (listView_testresults.Items.Count > 0)
            {
                string key;
                TestCase tc;

                foreach (ListViewItem tcitem in listView_testresults.SelectedItems)
                {
                    key = RallyDesk.CacheKey + tcitem.SubItems[5].Text + tcitem.SubItems[0].Text;
                    if (RallyDesk.Cache.Contains(key))
                    {
                        tc = (TestCase)RallyDesk.Cache.Get(key);
                        ViewTestCaseItemValuesOnForm(tc);
                    }
                    else
                        ClearFormItems();

                    break;
                }
            }
            else
                ClearFormItems();
        }
        private void ViewTestCaseItemValuesOnForm(TestCase tc)
        {
            this.txt_name.Text = tc.Name;
            //this.txt_description.Text = tc.Description;
            htmlEditor_Desc.HTMLText = "<html>" + tc.Description + "</html>";

            this.txt_Owner.Text = tc.Owner;
            this.txt_LastBuild.Text = tc.LastBuild;
            this.txt_LastVerdict.Text = tc.LastVerdict;

            this.txt_notes.Text = tc.Notes;
            this.txt_objective.Text = tc.Objective;
            this.txt_Type.Text = tc.Type;
           // this.txt_Method.Text = tc.Method;
            this.txt_Priority.Text = tc.Priority;
            this.txt_Risk.Text = tc.Risk;
            this.txt_Package.Text = tc.Package;
            this.txt_preConditions.Text = tc.PreConditions;
            this.txt_postConditions.Text = tc.PostConditions;
            htmlEditor_Validation.HTMLText = "<html>" + tc.ValidationInput + "</html>";
            //this.txt_validationInput.Text = tc.ValidationInput;
            htmlEditor_Expected.HTMLText = "<html>" + tc.ValidationExpectedResult + "</html>";
            //this.txt_expectedResult.Text = tc.ValidationExpectedResult;

            htmlEditor_Validation.IsEditMode = false;
            htmlEditor_Expected.IsEditMode = false;
            htmlEditor_Desc.IsEditMode = false;
            
            this.tabPage_TestCase.Text = "Test Case: " + tc.ID;
        }
        private void ClearFormItems()
        {
            this.txt_name.Text = string.Empty;
            //this.txt_description.Text = string.Empty;
            this.txt_notes.Text = string.Empty;
            this.txt_objective.Text = string.Empty;
            this.txt_Type.Text = string.Empty;
           // this.txt_Method.Text = string.Empty;
            this.txt_Priority.Text = string.Empty;
            this.txt_Risk.Text = string.Empty;
            this.txt_Package.Text = string.Empty;
            this.txt_preConditions.Text = string.Empty;
            this.txt_postConditions.Text = string.Empty;
            this.txt_LastBuild.Text = string.Empty;
            this.txt_LastVerdict.Text = string.Empty;
            this.txt_Owner.Text = string.Empty;
            //this.txt_validationInput.Text = string.Empty;
            //this.txt_expectedResult.Text = string.Empty;

            htmlEditor_Expected.HTMLText = "<html></html>";
            htmlEditor_Validation.HTMLText = "<html></html>";
            htmlEditor_Desc.HTMLText = "<html></html>";
            htmlEditor_Desc.IsEditMode = false;
            htmlEditor_Validation.IsEditMode = false;
            htmlEditor_Expected.IsEditMode = false;

            this.tabPage_TestCase.Text = "Test Case";

        }

        private void button2_Click(object sender, EventArgs e)
        {
            //this.Close();
         }

        private void SelectAll_checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (listView_testresults.Items.Count > 0 && SelectAll_checkBox.CheckState == CheckState.Checked)
            {
                foreach (ListViewItem tcitem in listView_testresults.Items)
                    tcitem.Checked = true;
                SelectAll_checkBox.Enabled = false;

            }

        }

        private void listView_testresults_MouseClick(object sender, MouseEventArgs e)
        {
            if (listView_testresults.Items.Count > 0)
            {
                if (listView_testresults.CheckedItems.Count < listView_testresults.Items.Count)
                {
                    SelectAll_checkBox.CheckState = CheckState.Unchecked;
                    SelectAll_checkBox.Enabled = true;
                }
                else
                    SelectAll_checkBox.Enabled = false;

            }

        }
        private void listView_testresults_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (listView_testresults.Items.Count > 0 && populatedata == true )
            {
                if (listView_testresults.CheckedItems.Count < listView_testresults.Items.Count)
                {
                    SelectAll_checkBox.CheckState = CheckState.Unchecked;
                    SelectAll_checkBox.Enabled = true;
                }
                else
                    SelectAll_checkBox.Enabled = false;




                if (listView_testresults.CheckedItems.Count > 0)
                {
                    deselect_checkBox.CheckState = CheckState.Unchecked;
                    deselect_checkBox.Enabled = true;
                }
                else
                    deselect_checkBox.Enabled = false;



            }
            

        }

        private void listView_testresults_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            Editorofdata();
        }



        private void bulk_button_Click(object sender, EventArgs e)
        {
            if (listView_testresults.CheckedItems.Count > 0)
            {

                string[] ResultRecord = new string[5];
                string[] UpdatedRecord = new string[5];
                if (editresult == null)
                    editresult = new frmTestResultEditor();
                ResultRecord[0] = string.Empty;
                ResultRecord[1] = string.Empty;
                ResultRecord[2] = string.Empty;
                ResultRecord[3] = string.Empty;
                ResultRecord[4] = string.Empty;

                //populate data back into the list view if updated record is not null
                UpdatedRecord = editresult.editdata(ResultRecord);
                if (UpdatedRecord!=null)      
                {
                    dataupdated = true;
                    foreach (ListViewItem tcitem in listView_testresults.Items)
                        {
                            if (tcitem.Checked == true)
                            {
                                    if (UpdatedRecord[2]!= string.Empty)
                                    tcitem.SubItems[2].Text = UpdatedRecord[2];

                                    if (UpdatedRecord[3] != string.Empty)
                                    tcitem.SubItems[3].Text = UpdatedRecord[3];

                                    if (UpdatedRecord[4] != string.Empty)
                                    tcitem.SubItems[4].Text = UpdatedRecord[4];

                                
                            }
                        }
                }
            }
            else
                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/NoRecordsSelected"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void SaveChanges_button_Click(object sender, EventArgs e)
        {
            string msConn;
            try
            {
                Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saving...";
                
                if (filename != string.Empty)
                {

                    if (System.IO.File.Exists(filename))
                    {
                        System.IO.File.Delete(filename);
                    }

                    msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";

                    //DataViewer NewData = new DataViewer();
                    OleDbConnection conn = new OleDbConnection();
                    conn.ConnectionString = msConn;
                    conn.Open();

                    System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("CREATE TABLE test " + "([TestCaseID] TEXT(50),[Description] LONGTEXT,[Verdict] TEXT(50),[Build] TEXT(50), [Notes] LONGTEXT,[TestCaseRef] TEXT(255))", conn);
                    cmd.ExecuteNonQuery();
                    foreach (ListViewItem tcitem in listView_testresults.Items)
                    {
                        cmd.CommandText = ("INSERT INTO test VALUES ('" + tcitem.SubItems[0].Text.Replace("'", "''") + "','" + tcitem.SubItems[1].Text.Replace("'", "''") + "','" + tcitem.SubItems[2].Text.Replace("'", "''") + "','" + tcitem.SubItems[3].Text.Replace("'", "''") + "','" + tcitem.SubItems[4].Text.Replace("'", "''") + "','" + tcitem.SubItems[5].Text.Replace("'", "''") + "')");
                        cmd.ExecuteNonQuery();

                    }

                    dataupdated = false;
                    //  MessageBox.Show("Changes Saved.", "Rally Desk");
                    conn.Close();
                    msConn = null;
                }
            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Ready";
            }

        }

        private void listView_testresults_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                Editorofdata();
            }
        }

        private void Editorofdata() 
        {
            if (listView_testresults.SelectedItems.Count > 0)
            {
                string[] ResultRecord = new string[5];
                string[] UpdatedRecord = new string[5];
                if (editresult == null)
                    editresult = new frmTestResultEditor();
                foreach (ListViewItem tcitem in listView_testresults.SelectedItems)
                {
                    ResultRecord[0] = tcitem.SubItems[0].Text;
                    ResultRecord[1] = tcitem.SubItems[1].Text;
                    ResultRecord[2] = tcitem.SubItems[2].Text;
                    ResultRecord[3] = tcitem.SubItems[3].Text;
                    ResultRecord[4] = tcitem.SubItems[4].Text;

                    //populate data back into the list view if updated record is not null
                    UpdatedRecord = editresult.editdata(ResultRecord);
                    if (UpdatedRecord != null)
                    {
                        dataupdated = true;
                        tcitem.SubItems[0].Text = UpdatedRecord[0];
                        tcitem.SubItems[1].Text = UpdatedRecord[1];
                        tcitem.SubItems[2].Text = UpdatedRecord[2];
                        tcitem.SubItems[3].Text = UpdatedRecord[3];
                        tcitem.SubItems[4].Text = UpdatedRecord[4];

                    }
                    break;
                }

            }
        }

        private void deselect_checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (listView_testresults.Items.Count > 0 && deselect_checkBox.CheckState == CheckState.Checked)
            {
                foreach (ListViewItem tcitem in listView_testresults.Items)
                    tcitem.Checked = false;
                 deselect_checkBox.Enabled = false;

            }
        
                
        }

        private void DataViewer_Shown(object sender, EventArgs e)
        {
            populatedata = true;
           
        }

        private void DataViewer_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dataupdated)
            {
                DialogResult res = new DialogResult();
                res = MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/SaveChanges"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);
                if (res == DialogResult.Yes)
                {
                    SaveChanges_button.PerformClick();
                }
                else if (res == DialogResult.Cancel)
                    e.Cancel = true;
                
            }
        }

        private void listView_testresults_ColumnClick(object sender, ColumnClickEventArgs e)
        {

            if (e.Column == 0)
            {
                if (listView_testresults.Items.Count > 0 )
                {
                    if (listView_testresults.CheckedItems.Count > 0)
                    {
                        foreach (ListViewItem tcitem in listView_testresults.Items)
                            tcitem.Checked = false;
                        deselect_checkBox.Enabled = false;
                    }
                }
                
                if (listView_testresults.Sorting == SortOrder.Ascending)
                    listView_testresults.Sorting = SortOrder.Descending;
                else
                    listView_testresults.Sorting = SortOrder.Ascending;

            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            if (this.listView_testresults.CheckedItems.Count > 0)
            {
                if (this.listView_testresults.CheckedItems.Count == this.listView_testresults.Items.Count)
                {

                    if (MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/DeleteAllRecordsWarning"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                        return;

                }
                foreach (ListViewItem tcitem in this.listView_testresults.Items)
                {
                    if (tcitem.Checked == true)
                    {
                        tcitem.Remove();
                    }
                    
                }
                this.dataupdated = true;
                this.RecNum_label.Text = Convert.ToString(this.listView_testresults.Items.Count);
            }
        }

        private void btn_SaveAs_Click(object sender, EventArgs e)
        {
            string msConn;
            try
            {
                  SaveFileDialog op1 = new SaveFileDialog();
                    op1.DefaultExt = ".xls";
                    op1.Filter = "Excel(*.xls)|*.xls";
                    if (op1.ShowDialog() == DialogResult.OK)
                    {
                        Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Saving...";
                        filename = op1.FileName;
                        if (filename == string.Empty)
                            filename = null;
                        op1.Dispose();
                        if (filename != null)
                        {

                            if (System.IO.File.Exists(filename))
                            {
                                System.IO.File.Delete(filename);
                            }

                            msConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filename + ";" + "Extended Properties=\"Excel 8.0;HDR=YES\"";

                            //DataViewer NewData = new DataViewer();
                            OleDbConnection conn = new OleDbConnection();
                            conn.ConnectionString = msConn;
                            conn.Open();

                            System.Data.OleDb.OleDbCommand cmd = new OleDbCommand("CREATE TABLE test " + "([TestCaseID] TEXT(50),[Description] TEXT(255),[Verdict] TEXT(50),[Build] TEXT(50), [Notes] LONGTEXT,[TestCaseRef] TEXT(255))", conn);
                            cmd.ExecuteNonQuery();
                            foreach (ListViewItem tcitem in listView_testresults.Items)
                            {
                                cmd.CommandText = ("INSERT INTO test VALUES ('" + tcitem.SubItems[0].Text.Replace("'", "''") + "','" + tcitem.SubItems[1].Text.Replace("'", "''") + "','" + tcitem.SubItems[2].Text.Replace("'", "''") + "','" + tcitem.SubItems[3].Text.Replace("'", "''") + "','" + tcitem.SubItems[4].Text.Replace("'", "''") + "','" + tcitem.SubItems[5].Text.Replace("'", "''") + "')");
                                cmd.ExecuteNonQuery();

                            }

                            dataupdated = false;
                            //  MessageBox.Show("Changes Saved.", "Rally Desk");
                            conn.Close();
                            msConn = null;
                            this.Text = "Create Test Results-[" + filename + "]";
                        }
                }
            }
            catch (System.IndexOutOfRangeException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Data.OleDb.OleDbException)
            {

                MessageBox.Show(m_ResourceManager.GetString("memo://rallydesk/InvalidTemplate"), m_ResourceManager.GetString("memo://rallydesk/RallyDeskCaption"), MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                Rally_Dekstop.Program.RallyMain.toolStripStatusLabel.Text = "Ready";
            }


        }

        

        
    
    }

       
        
        
    
}